package com.helper;

import com.dao.*;
import com.model.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

public class Util {

	public static int questionCount(String str) {
		int count = 0;
		int idx = str.indexOf(";");
		while(idx != -1) {
			count++;
			idx = str.indexOf(";", idx+1);
		}
		return count/2;
	}
	
	public static int getQuestionId(String str, int num) {
		if(num == 1) {
			int nest_idx = str.indexOf(";", 1);
			String num_str = str.substring(1, nest_idx);
			return Integer.parseInt(num_str);
		}
		int count = 0;
		int idx = str.indexOf(";");
		while(idx != -1) {
			count++;
			if(count == (num-1)*2 + 1) {
				break;
			}
			idx = str.indexOf(";", idx+1);
		}
		int nest_idx = str.indexOf(";", idx+1);
		String num_str = str.substring(idx+1, nest_idx);
		return Integer.parseInt(num_str);
	}

	public static String getDateString() {
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		return now.format(formatter);
	}

	public static float[] scoreCalculate(int userId, Exam exam) {

		AnswerDao answerDao = new AnswerDao();
		ExamDao examDao = new ExamDao();
		PaperDao paperDao = new PaperDao();
		ScoreSetDao scoreSetDao = new ScoreSetDao();

		ScoreSet scoreSet = scoreSetDao.getByPaperId(exam.getPaperId());
		Paper paper = paperDao.getById(exam.getPaperId());
		int objQuestionsNum = examDao.getTotalQuestionsNum(exam.getId()) - Util.questionCount(paper.getDiscussId());

		int correctNum = 0;
		float score = 0f;
		float rate = 0f;

		for(int i=1; i<=objQuestionsNum; ++i) {
			Answer answer = answerDao.getByExamNumUser(exam.getId(), i, userId);
			if(answer != null) {
				Map<String , Integer> map = paperDao.getQuestionId(i, exam.getPaperId());
				for(String key: map.keySet()) {
					Integer queId = map.get(key);
					if(key.equals("C")) {
						QuestionChoiceDao cdao = new QuestionChoiceDao();
						QuestionChoice c = cdao.getById(queId);
						if(c.getAnswer().equals(answer.getContent())) {
							correctNum += 1;
							score += scoreSet.getChoiceScore();
						}
					}
					if(key.equals("M")) {
						QuestionChoiceDao mdao = new QuestionChoiceDao();
						QuestionChoice c = mdao.getById(queId);
						if(c.getAnswer().replace(",", "").equals(answer.getContent().replace(";",""))) {
							correctNum += 1;
							score += scoreSet.getMultichoiceScore();
						}
					}
					if(key.equals("J")) {
						QuestionJudgeDao jdao = new QuestionJudgeDao();
						QuestionJudge j = jdao.getById(queId);
						if(j.getAnswer().equals(answer.getContent().toLowerCase())) {
							correctNum += 1;
							score += scoreSet.getJudgeScore();
						}
					}
				}
			}
		}

		if(objQuestionsNum>0)
			rate = correctNum * 1.0f / objQuestionsNum;

		return new float[]{score, rate};
	}
}
